package hu.gar.web.listener;

import hu.gar.common.service.RoleService;
import hu.gar.common.service.UserService;
import hu.gar.vo.RoleVO;
import hu.gar.vo.UserVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class InitListener implements ApplicationListener<ContextRefreshedEvent> {
	@Autowired
	RoleService roleService;

	@Autowired
	private UserService userService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		RoleVO role = roleService.getRoleByName("ADMIN");
		if (role == null) {
			RoleVO roleVo = new RoleVO();
			roleVo.setRole("ADMIN");
			roleService.createRole(roleVo);
		}

		role = roleService.getRoleByName("USER");
		if (role == null) {
			RoleVO roleVo = new RoleVO();
			roleVo.setRole("USER");
			roleService.createRole(roleVo);
		}

		UserVO admin = userService.findByName("admin");
		if (admin == null) {
			UserVO userVO = new UserVO();
			userVO.setUsername("admin");
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			userVO.setPassword(encoder.encode("admin"));
			userVO = userService.addUser(userVO);

			RoleVO roleVO = roleService.getRoleByName("ADMIN");
			userService.addRoleToUser(userVO.getId(), roleVO.getId());
		}
	}

}
